package com.ipartek.formacion.ficheros;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

/**
 * Clase para comparar tiempos entre el FileWriter y el BufferedWriter para
 * escribir 20.000.000 de registros en un fichero
 * 
 * @author Iker
 * 
 */
public class FileWriterVsBufferedWriter {

	static final String PATH_FILE1 = "data/datos3.txt";
	static final String PATH_FILE2 = "data/datos4.txt";
	static FileWriter fr;
	static FileWriter fr2;
	static BufferedWriter br;

	public static void main(String[] args) throws IOException {
		try {
			// FileWriter
			fr = new FileWriter(PATH_FILE1);
			long ini = System.currentTimeMillis();
			Random randomGenerator = new Random();
			for (int i = 0; i < 20000000; i++) {
				int c = randomGenerator.nextInt(97);
				if (c == 96) {
					fr.write(13);
				} else {
					fr.write(c + 32);
				}
			}
			long fin = System.currentTimeMillis();
			System.out
					.println("Tiempo en escribir 20.000.000 de caracteres con FileWriter: "
							+ (fin - ini) + "ms");

			// BufferedWriter
			fr2 = new FileWriter(PATH_FILE2);
			br = new BufferedWriter(fr2);
			ini = System.currentTimeMillis();
			for (int i = 0; i < 20000000; i++) {
				int c = randomGenerator.nextInt(97);
				if (c == 96) {
					br.write(13);
				} else {
					br.write(c + 32);
				}
			}
			fin = System.currentTimeMillis();
			System.out
					.println("Tiempo en escribir 20.000.000 de caracteres con BufferedWriter: "
							+ (fin - ini) + "ms");
		} catch (FileNotFoundException e) {
			System.out.println("No encuentra el fichero: " + PATH_FILE1);
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IOException");
			e.printStackTrace();
		} catch (Exception e) {
			System.out.println("Excepcion general");
			e.printStackTrace();
		} finally {
			fr.close();
			br.close();
		}

	}

}
